package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handleSQLException(SQLIntegrityConstraintViolationException exception) {
        log.error("异常信息: {}", exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")) {
            Pattern compile = Pattern.compile("Duplicate entry '(.*?)' for key");
            Matcher matcher = compile.matcher(exception.getMessage());
            if (matcher.find()) {
                String group = matcher.group(1);
                log.info("账号为: {}",group);
                return R.error(group + "已存在");
            }
        }
        return R.error("服务器错误");
    }

    @ExceptionHandler(BusinessException.class)
    public R<String> handleException(BusinessException exception) {
        log.error("异常信息: {}", exception.getMessage());
        return R.error(exception.getMessage());
    }
}
